<?php


namespace app\common\controller;


use addons\epay\library\Service;
use Endroid\QrCode\QrCode;
use think\Db;
use think\Response;

class Util
{
//    private $Util;
//
//public function __construct()
//{
//    $this->Util = new Util();
//}

    public static function getInviteCode()
    {
        $Util = new Util();
        /* 生成唯一邀请码 START*/
        $inviteCode = $Util->createRecommendCode();
        $r = true;
        while ($r) {
            $r = Db::name('student')->where('invite_code', $inviteCode)->find();
            $r1 = Db::name('teacher')->where('invite_code', $inviteCode)->find();
            if ($r || $r1) {
                $inviteCode = $Util->createRecommendCode();
            }
        }
        return $inviteCode;
    }

    public function createRecommendCode()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d')
            . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            $d = '',
            $f = 0;
            $f < 6;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }

    public static function getTree($data, $id = 0)
    {
        //初始化儿子
        $child = [];
        //循环所有数据找$id的儿子
        foreach ($data as $key => $datum) {
            //找到儿子了
            if ($datum['pid'] == $id) {
                //保存下来继续找儿子的儿子
                $child[$datum['id']] = $datum;
                //先去掉自己,自己不可能是自己的儿子
                unset($data[$key]);
                //递归找,并把找到的儿子存在child里
                $child[$datum['id']]['child'] = self::getTree($data, $datum['id']);
            }
        }
        return $child;
    }

    public static function checkEmpty($str, $type = 'string')
    {
        $flag = true;
        switch ($type) {
            case "string":
                $flag = is_string($str);
                break;
            case "array" :
                $flag = is_array($str);
                break;
        }
        return !empty($str) && $flag;
    }

    /**
     * Notes:设置默认值
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 11:08
     * @param $data
     * @param $field
     * @param string $default
     * @return mixed
     */
    public static function setDefault($data, $field = '', $default = '')
    {
        foreach ($data as $k => &$v) {
            if (in_array($k, is_array($field) ? $field : array_keys($data))) {
                $v = self::checkEmpty($v) ? $v : $default;
            }
        }
        foreach (array_diff(is_array($field) ? $field : array_keys($data), array_keys($data)) as $k => $v) {
            $data[$v] = '';
        }
        return $data;
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/25
     * @Time: 16:43
     * @Interface changeAdminOrUser
     * @param $admin_id
     * @param string $type
     * @param $account_status
     * @param $user_id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function changeAdminOrUser($admin_id, $account_status, $user_id = '')
    {
        switch ($account_status) {
            case '1':
                if (!empty($admin_id)) {
                    $myupdate['id'] = $admin_id;
                    $myupdate['status'] = 'normal';
                    Db::name('admin')->update($myupdate);
                }
                if (!empty($user_id)) {
                    $myupdate['id'] = $user_id;
                    Db::name('user')->where('id', $myupdate['id'])->update($myupdate);
                }
                break;

            case '0':
                if (!empty($admin_id)) {
                    $myupdate['id'] = $admin_id;
                    $myupdate['status'] = 'hidden';
                    Db::name('admin')->where('id', $myupdate['id'])->update($myupdate);
                }
                if (!empty($user_id)) {
                    $myupdate['id'] = $user_id;
                    Db::name('user')->where('id', $myupdate['id'])->update($myupdate);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 根据时间戳返回星期几
     * @param string $time 时间戳
     * @return
     */
    public static function weekday($time)
    {
        if (is_numeric($time)) {
            $weekday = array('日', '一', '二', '三', '四', '五', '六');
            return "周" . $weekday[date('w', $time)];
        }
        return false;
    }

    /**
     * Notes:生成订单编号
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 18:29
     * @return string
     */
    public static function getOrderNumber()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

    /**
     * Notes:产出唯一订单号
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 18:34
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function createOnlyOrderNumber()
    {
        $flag = true;
        $orderNumber = '';
        while ($flag) {
            $orderNumber = self::getOrderNumber();
            $res = Db::name('order')->where('sn', $orderNumber)->find();
            $flag = self::checkEmpty($res, 'array');
        }
        return $orderNumber;
    }

    /** 获取当时时间
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/26
     * @Time: 12:45
     * @Interface getNowDateTime
     * @return false|string
     */
    public static function getNowDateTime()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * Notes:xml转数组
     * @param $xmlStr
     * @return array
     */
    public static function xmlToArray($xmlStr): array
    {
        $msg = [];
        $postStr = $xmlStr;
        $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        return $msg;
    }

    /**
     * Notes:微信退款
     * User: XingLiangRen
     * Date: 2020/9/1
     * Time: 9:48
     * @param $out_trade_no 订单号
     * @param $out_refund_no 退款单号
     * @param $total_fee 总金额金额
     * @param $refund_fee 退款金额
     * @param $refund_desc 退款描述
     * @param $notify_url 回调地址
     * @return array|bool
     */
    public static function weChatRefund($out_trade_no, $out_refund_no, $total_fee, $refund_fee, $refund_desc, $notify_url)
    {
        $config = [
            'notify_url' => $notify_url
        ];
        $pay = Service::createPay('wechat', $config);
        $orderData = [
            'out_trade_no' => $out_trade_no,
            'out_refund_no' => $out_refund_no,
            'total_fee' => $total_fee,
            'refund_fee' => $refund_fee,
            'refund_desc' => $refund_desc,
            'notify_url' => $notify_url,
        ];
        $res = $pay->driver('wechat')->gateway('scan')->refund($orderData);
        self::write_log(\GuzzleHttp\json_encode($res, JSON_UNESCAPED_UNICODE));
        return $res;
    }


    /**
     * [write_log 写入日志]
     * @param  [type] $data [写入的数据]
     * @return [type]      [description]
     */

    public static function write_log($data = '')
    {

        $years = date('Y-m');

        //设置路径目录信息

        $url = './log/' . $years . '/' . date('Ymd') . '_request_log.txt';

        $dir_name = dirname($url);

//        dump($dir_name);
//        die();

        //目录不存在就创建

        if (!file_exists($dir_name)) {

            //iconv防止中文名乱码

            if (!mkdir($concurrentDirectory = iconv("UTF-8", "GBK", $dir_name), true) && !is_dir($concurrentDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }

            chmod($dir_name, 0777);

        }

        $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建

        date_default_timezone_set('PRC');

        flock($fp, LOCK_EX);

        fwrite($fp, date("Y-m-d H:i:s") . var_export($data, true) . "\r\n");//写入文件

        flock($fp, LOCK_UN);

        fclose($fp);//关闭资源通道

    }

    public static function getWechatNotifyxData()
    {
        // 接受微信回调数据
        $testxml = file_get_contents("php://input");
        // 将xml数据转为数组
        $result = Util::xmlToArray($testxml);
        // 处理逻辑
        Util::write_log(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    public static function wechatSuccess()
    {
        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
    }

    /**
     * 生成二维码
     * @return Response
     */
    public static function qrcode($text, $size = 300, $padding = 15, $errorcorrection = 'medium',
                                  $foreground = '#ffffff', $background = '#000000', $logosize = 50,
                                  $label = '', $labelfontsize = 100, $labelhalign = 'medium', $labelvalign = 'medium'
    )
    {

        // 前景色
        list($r, $g, $b) = sscanf($foreground, "#%02x%02x%02x");
        $foregroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        // 背景色
        list($r, $g, $b) = sscanf($background, "#%02x%02x%02x");
        $backgroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        $qrCode = new QrCode();
        $qrCode
            ->setText($text)
            ->setSize($size)
            ->setPadding($padding)
            ->setErrorCorrection($errorcorrection)
            ->setForegroundColor($foregroundcolor)
            ->setBackgroundColor($backgroundcolor)
            ->setLogoSize($logosize)
            ->setLabelFontPath(ROOT_PATH . 'public/assets/fonts/Times New Roman.ttf')
            ->setLabel($label)
            ->setLabelFontSize($labelfontsize)
            ->setLabelHalign($labelhalign)
            ->setLabelValign($labelvalign)
            ->setImageType(QrCode::IMAGE_TYPE_PNG);
        //也可以直接使用render方法输出结果
        //$qrCode->render();
        return new Response($qrCode->get(), 200, ['Content-Type' => $qrCode->getContentType()]);
    }

    /**
     * 判断字符串是否为 Json 格式
     *
     * @param string $data Json 字符串
     * @param bool $assoc 是否返回关联数组。默认返回对象
     * @return array|bool|object 成功返回转换后的对象或数组，失败返回 false
     */
    static function isJson($data = '', $assoc = false)
    {
        $data = json_decode($data, $assoc);
        if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
            return $data;
        }
        return false;
    }

    // 获取教师登录信息
    public static function getUserInfo($id,$field = 'user_id')
    {
        return Db::name('teacher')->where($field, $id)->find();
    }
}